package org.ayachinene.leetcode.utils;

import org.jetbrains.annotations.NotNull;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

class CommonUtils {

    private static final String DEFAULT_SEPARATOR = ",";

    private static final String DEFAULT_LEFT_BORDER = "[";
    private static final String DEFAULT_RIGHT_BORDER = "]";

    static @NotNull List<String> extract(@NotNull String s) {
        return extract(s, DEFAULT_SEPARATOR);
    }

    static @NotNull List<String> extract2D(@NotNull String s) {
        if (!StringUtils.hasText(s)) {
            throw new IllegalArgumentException();
        }
        s = StringUtils.trimAllWhitespace(s);
        if (!(s.startsWith(DEFAULT_LEFT_BORDER + DEFAULT_LEFT_BORDER) &&
                s.endsWith(DEFAULT_RIGHT_BORDER + DEFAULT_RIGHT_BORDER))) {
            throw new IllegalArgumentException();
        }
        s = s.substring(1, s.length() - 1);
        return extract(s, "],\\[").stream()
                .map(arrayStr -> DEFAULT_LEFT_BORDER + arrayStr + DEFAULT_RIGHT_BORDER)
                .collect(Collectors.toList());
    }

    /**
     * 提取边界内的元素，其中元素间以特定分割符分割
     * 例如：[1,2,3,4]
     * 左边界为"["，右边界为"]"，分割符为","
     * @param s 要提取的字符串
     * @param separator 分割符
     * @return 元素列表
     */
    static @NotNull List<String> extract(@NotNull String s, @NotNull String separator) {
        if (!StringUtils.hasText(s) || !StringUtils.hasText(separator)) {
            throw new IllegalArgumentException();
        }
        s = StringUtils.trimAllWhitespace(s);
        separator = StringUtils.trimAllWhitespace(separator);
        if (!(s.startsWith(DEFAULT_LEFT_BORDER) && s.endsWith(DEFAULT_RIGHT_BORDER))) {
            throw new IllegalArgumentException();
        }
        s = s.substring(1, s.length() - 1);
        if (!StringUtils.hasText(s)) {  // "[ ]", "[]"
            return new ArrayList<>();
        }
        return Arrays.asList(s.split(separator));
    }
}
